package game.leon.engine.script;

/**
 * 一个缓冲区域
 * 之所以需要一个缓冲区, 是因为不应该填满, 毕竟有些判断是需要反复的
 * 跟source无关的一个buffer, 只需要负责填充就行了
 * User: bianpeng
 * Date: 12-2-3
 */
public class Buffer {
    private byte[] buffer;
    private int offset; // 当前偏移
    public Buffer(int bufsize) {
        assert bufsize >= 2;
        buffer = new byte[bufsize];
        offset = bufsize;
    }
    //-----------------------------------------------------------------
    // 读取
    //-----------------------------------------------------------------
    public int look() {
        return look(0);
    }
    public int look(int ahead) {
        assert ahead >= 0;
        return buffer[offset + ahead];
    }
    public int advance(int ahead) {
        assert ahead >= 0;
        offset += ahead;
        return offset;
    }
    public boolean full() {
        return offset >= buffer.length;
    }
    public int capacity() {
        return buffer.length;
    }
    //-----------------------------------------------------------------
    // 填充
    //-----------------------------------------------------------------
    public void fill(byte[] src, int start, int count) {
        assert count <= capacity();
        offset = capacity() - count;
        for(int i = 0; i < offset; ++i) {
            buffer[i] = buffer[count + i];
        }
        for(int i = 0; i < count; ++i) {
            buffer[i + offset] = src[i + start];
        }
    }
}
